package meijuli.com.join51.business.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.jhx.common.cache.SimpleCache;
import com.jhx.common.http.ApiManager;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;
import com.jhx.common.model.Event;
import com.jhx.common.model.EventBean;
import com.jhx.common.model.User;
import com.jhx.common.utils.Constants;
import com.jhx.common.utils.ToastUtil;
import com.jhx.common.utils.UserManager;
import com.jhx.common.widget.CommonDialog;
import com.jhx.video.videorecord.VideoRecordActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.lang.ref.WeakReference;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.fragment.ReviewAfterFragment;
import meijuli.com.join51.business.fragment.ReviewBeforeFragment;
import meijuli.com.join51.business.fragment.ReviewingFragment;
import meijuli.com.join51.business.message.MessageActivity;
import meijuli.com.join51.business.model.AppBean;
import meijuli.com.join51.business.model.Status;
import meijuli.com.join51.business.service.ApiService;
import meijuli.com.join51.business.utils.LogUtils;
import meijuli.com.join51.business.utils.UpdateCheck;
import retrofit2.Call;

/**
 * 首页
 *
 * @author
 */
public class MainActivity extends BaseActivity {
    public static final String KEY_USER = "key_user";
    public static final String KEY_STATUS = "key_status";
    /**
     * 强制更新
     */
    private final static int COMPEL_UPDATE = 1;
    private static final int MSG_SET_ALIAS = 1001;
    private CommonDialog mUpdateDialog;
    SwipeRefreshLayout mSwipeRefreshLayout;
    ImageView mMessageIcon;
    ImageView mCameraImage;
    private CommonDialog mDialog;
    private long mStartTime = 0;
    private User mUser;
    private Status mStatus;
    /**
     * 记录是否强制升级，默认不是
     */
    private boolean mISCompelUpdate = false;
    private Runnable mRunnable;

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    LogUtils.i(TAG, logs);
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    LogUtils.i(TAG, logs);
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    LogUtils.e(TAG, logs);
            }
        }
    };
    private final InnerHandler mHandler = new InnerHandler(this, mAliasCallback);
    private Call<HttpResponse<Status>> mCall;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        setContentView(R.layout.activity_main);
        mSwipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
        mMessageIcon = findViewById(R.id.message_icon);
        mCameraImage = findViewById(R.id.img_camera);
        mCameraImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent;
                switch (mStatus.getAuthStatus()) {
                    case Constants.ApprovalStatus.APPROVAL_SUCCESS:
                        intent =new Intent(MainActivity.this, VideoRecordActivity.class);
                        startActivity(intent);
                        break;
                    default:
                        intent = new Intent(MainActivity.this, SettingActivity.class);
                        startActivity(intent);
                        break;
                }
            }
        });
        mMessageIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onMessageIconClick();
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(ContextCompat.getColor(this, R.color.black));
        }

        if (UserManager.get().checkUserNull(this)) {
            mUser = new User();
            mUser.setIsDiscount(Constants.DISCOUNT_UN_SET);
        } else {
            mUser = UserManager.get().getUser();
        }

        // 调用 Handler 来异步设置别名
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, mUser.getDmId() + ""));
        requestAuthStatus(mUser);

        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mUser = UserManager.get().getUser();
                requestAuthStatus(mUser);
            }
        });
        checkUpdate();
    }

    private void toFragment(Status status, User user) {
        Fragment fragment;
        switch (status.getAuthStatus()) {
            case Constants.ApprovalStatus.APPROVALING:
                fragment = ReviewingFragment.newInstance(user);
                break;
            case Constants.ApprovalStatus.APPROVAL_SUCCESS:
                fragment = ReviewAfterFragment.newInstance(status);
                break;
            default:
                fragment = ReviewBeforeFragment.newInstance(user, status);
                break;
        }
        addFragment(fragment);
        if(status.getAuthStatus() == Constants.ApprovalStatus.APPROVAL_ERROR) {
            if(mDialog == null) {
                mDialog = new CommonDialog(this);
            }
            mDialog.dismiss();
            mDialog.setTitle("认证失败");
            mDialog.setMessage(status.getRemark());
            mDialog.getCancelText().setVisibility(View.GONE);
            mDialog.setOnClickListener(new CommonDialog.OnClickListener() {
                @Override
                public void onConfirmClick(View view) {

                }

                @Override
                public void onCancelClick(View view) {

                }
            });
            if(!mDialog.isShowing()) {
                mDialog.show();
            }
        }
    }

    public void requestAuthStatus(final User user) {
        if (mSwipeRefreshLayout != null && !mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(true);
        }
        getAuthStatus(user);
    }

    private void getAuthStatus(final User user) {
        mCall = ApiManager.get().getApiService(ApiService.class).getAuthStatus();
        HttpRequest.getRequest().autoRecycle(this).start(mCall, new ResponseCallback<Status>() {

            @Override
            public void onSuccess(String url, Status data) {
                dismissRefreshDelay();
                if (data == null) {
                    return;
                }
                mStatus = data;
                user.setType(mStatus.getType());
                user.setDmId(mStatus.getDmId());
                user.setLevelDesc(mStatus.getLevelDesc());
                user.setEndTime(mStatus.getEndTime());
                user.setAuthStatus(mStatus.getAuthStatus());
                user.setHeadImage(mStatus.getHeadImg());
                user.setBusinessName(mStatus.getBusinessName());
                UserManager.get().setUser(user);
                SimpleCache.Companion.put(Constants.IS_SHOW_EXPIRED, true);
                if(mStatus.getAuthStatus() == Constants.ApprovalStatus.APPROVAL_SUCCESS) {
                    mCameraImage.setImageResource(R.mipmap.icon_camera);
                } else {
                    mCameraImage.setImageResource(R.mipmap.icon_setting);
                }
                toFragment(mStatus, user);
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                mSwipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    private void dismissRefreshDelay() {
        if (mRunnable == null) {
            mRunnable = new Runnable() {
                @Override
                public void run() {
                    if (!isFinishing() && mSwipeRefreshLayout != null) {
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                }
            };
        }
        mSwipeRefreshLayout.postDelayed(mRunnable, 1000);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        LogUtils.d("TT", "onNewIntent>>>>>>");
        if (intent == null) {
            return;
        }
        User user = UserManager.get().getUser();
        if (user != null) {
            requestAuthStatus(user);
        }
    }

    private void checkUpdate() {
        UpdateCheck.getUpdateCheck().setUpdateCheckListener(new UpdateCheck.OnUpdateCheckListener() {
            @Override
            public void onUpdateCheckStart() {
            }

            @Override
            public void onUpdateCheckComplete(final AppBean appBean, String currentVersion) {
                dismissDialog();
                if(mUpdateDialog == null) {
                    mUpdateDialog = new CommonDialog(MainActivity.this);
                }
                mUpdateDialog.setMessage(appBean.getAppTxt());
                mUpdateDialog.setTitle(appBean.getAppLable());
                mUpdateDialog.setConfirmBtn("升级");
                if(UpdateCheck.toVersionCode(appBean.getMainVersion()) > UpdateCheck.toVersionCode(currentVersion)
                    && UpdateCheck.toVersionCode(currentVersion) >= UpdateCheck.toVersionCode(appBean.getMinVersion())) {
                    //非强制更新
                    if (appBean.getFlag() == COMPEL_UPDATE) {
                        mISCompelUpdate = true;
                        mUpdateDialog.setCancelBtn("退出");
                        mUpdateDialog.setCancelable(false);
                    } else {
                        mISCompelUpdate = false;
                        mUpdateDialog.setCancelBtn("取消");
                    }
                    mUpdateDialog.setOnClickListener(new CommonDialog.OnClickListener() {
                        @Override
                        public void onConfirmClick(View view) {
                            DownloadActivity.start(MainActivity.this, appBean);
                        }

                        @Override
                        public void onCancelClick(View view) {
                            if(appBean.getFlag() == COMPEL_UPDATE) {
                                System.exit(0);
                            }
                        }
                    });
                    if(!mUpdateDialog.isShowing()) {
                        mUpdateDialog.show();
                    }
                }
            }

            @Override
            public void onUpdateCheckNew() {
                dismissDialog();
                ToastUtil.getInstance().showToast(MainActivity.this, "已是最新版本");
            }

            @Override
            public void onUpdateCheckFail() {
                dismissDialog();
            }
        }).check();
    }

    private void toLogin() {
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onBackPressed() {
        long mPressedTime = System.currentTimeMillis();
        if (mPressedTime - mStartTime > 2 * 1000) {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mStartTime = mPressedTime;
        } else {
            finish();
        }
    }

    @Subscribe()
    public void onEvent(EventBean eventBus) {
        if (eventBus.getStatus() == EventBean.STATUS_LOGIN_OUT) {
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        } else if (eventBus.getStatus() == EventBean.STATUS_UPDATE_MAIN) {
            mUser = UserManager.get().getUser();
            requestAuthStatus(mUser);
        } else if (eventBus.getStatus() == EventBean.STATUS_MESSAGE) {
            onMessageIconClick();
        }
    }

    private void onMessageIconClick() {
        Intent intent = new Intent(MainActivity.this, MessageActivity.class);
        startActivity(intent);
    }

    @Subscribe
    public void onEvent(Event event) {
        if(event.getData() instanceof Status) {
            toFragment((Status) event.getData(), mUser);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.removeCallbacks(mRunnable);
        }
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    private static class InnerHandler extends Handler {
        private final WeakReference<MainActivity> mMainActivityWeakReference;
        private final TagAliasCallback mAliasCallback;

        InnerHandler(MainActivity mainActivity, TagAliasCallback aliasCallback) {
            mMainActivityWeakReference = new WeakReference<>(mainActivity);
            mAliasCallback = aliasCallback;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MainActivity mainActivity = mMainActivityWeakReference.get();
            if (mainActivity != null) {
                switch (msg.what) {
                    case MSG_SET_ALIAS:
                        JPushInterface.setAliasAndTags(mainActivity, (String) msg.obj, null, mAliasCallback);
                        break;
                    default:

                        break;
                }
            }
        }
    }
}
